package com.bullsora.kindlerss.feedsmanagement

import com.bullsora.kindlerss.model.Feed
import com.bullsora.kindlerss.model.FeedUrl
import org.apache.log4j.Logger

/**
 *
 * @author Sorin Buliarca
 */
class FeedService {

  private static def log = Logger.getLogger(this)

  /**
   * Saves the feed together with its Url.
   *
   * @param feed the feed to be saved
   * @return the saved feed.
   */
  Feed saveFeedWithUrl(Feed feed) {
    if (feed.url) {
      log.info("feed url is in place")
      /*  check if the url of the FeedUrl has changed.  */
      if (feed.url.id) {
        Feed.withSession {session ->
          session.clear()
          def existingFeedUrl = FeedUrl.get(feed.url.id)
          if (existingFeedUrl && existingFeedUrl.url != feed.url.url) {
            feed.url.discard()
            // force creating a new feed url so that the old one is kept
            feed.url = new FeedUrl(feed.url.properties - [id : '', version : ''])
          }
        }
      }

      /*  save the feed url if it doesn't have an id yet  */
      if (!feed.url.id) {
        if (!feed.url.save()) {
          return null
        }
      }
    }

    return feed.save()
  }
}
